function PRE4_GenerateAverageRegions()
%PRE4_GENERATEAVERAGEREGIONS
%  Go through all regions and generate files that average all participating
%  electrodes

% Access the preloaded database..
global Database;

%% Setup the procedure
% To do all regions for all subjects...

allConditions = sort(unique(Database.conditions(:,strcmp(Database.conditions_header,'Name'))));
allSubjects = GetSubjects;
allRegions = GetRegions;

% To do a smaller selection
% allConditions = { ...
%     'Sphere Ambiguous Response', ...
%     'Sphere Unambiguous Response', ...
%     'Sphere Unambiguous Stimulus', ...
%     'FaceHouse Ambiguous Response', ...
%     'FaceHouse Unambiguous Response', ...
%     'FaceHouse Unambiguous Stimulus', ...
%     };
% allSubjects = {'CW', 'JF', 'DS'};
% allRegions = {'occ', 'para'};


%% Loop through all subjects, conditions and regions
for iSubject = 1:length(allSubjects)
    subject = Like(GetSubjects, allSubjects{iSubject});
    
    for iCondition = 1:length(allConditions)
        condition = allConditions{iCondition};
        
        for iRegion = 1:length(allRegions)
            % Get the strings instead of the index, and verify where needed..
            region = Like(GetRegions, allRegions{iRegion});
            disp(' ');
            disp(['Subject/Region: ' subject '/' region]);
            
            %% Loop through all electrodes for this subject-region
            electrodes = GetRegionElectrodes(subject, region);
            subject_SELECT = strcmp(Database.timefrequency(:,strcmp(Database.timefrequency_header,'Subject')), subject);
            condition_SELECT = strcmp(Database.timefrequency(:,strcmp(Database.timefrequency_header,'Condition')), condition);
            electrodes_SELECT = false(size(Database.timefrequency, 1),1);
            for iElec = 1:length(electrodes)
                electrodes_SELECT = electrodes_SELECT | ...
                    strcmp(Database.timefrequency(:,strcmp(Database.timefrequency_header,'Channel')), electrodes{iElec});
            end
            % Retrieve the correct rows that should be merged
            rows_SELECT = subject_SELECT & condition_SELECT & electrodes_SELECT;
            if sum(rows_SELECT)>0  % This ensures there is at least ONE
                
                timefrequencyFiles = Database.timefrequency(rows_SELECT,:);
                % Check for similar TIMES, FREQUENCIES
                TIMES = timefrequencyFiles(:,strcmp(Database.timefrequency_header,'Times'));
                FREQS = timefrequencyFiles(:,strcmp(Database.timefrequency_header,'Frequencies'));
                for i = 2:length(TIMES);
                    if NumbersUnequal(TIMES{1}, TIMES{i}) | NumbersUnequal(FREQS{1}, FREQS{i})
                        error('Not all files have the same TF properties.');
                        % Hier moet nog wat bijgebouwd worden als dit moet
                        % werken, maar eigenlijk is het niet nodig.. gewoon de
                        % hele TF-batch opnieuw runnen als je met andere
                        % parameters wil TFfen.
                    end
                end
                
                %% Load data
                disp('Will merge data from ..');
                clear DATA
                for i = 1:size(timefrequencyFiles)
                    currentFile = timefrequencyFiles{i, strcmp(Database.timefrequency_header,'Filename')};
                    disp(['+ ' currentFile]);
                    DATA(i) = load(currentFile);
                end
                disp('.. into new channel data');
                
                %% Create the average power and other fields
                newDATA = zeros([size( DATA(1).power ) length(DATA)]);
                for i = 1:length(DATA);
                    newDATA(:,:,:,i) = DATA(i).power;
                end;
                power = mean(newDATA,4); % This will only work if number of epochs is the same for all electrodes.
                times = DATA(1).times;
                frequencies = DATA(1).frequencies;
                channel = region;
                channelType = 'Region';
                nrOfEpochs = size(power,3); %#ok<NASGU>
                
                filename = [Database.Path.TimeFrequencyData subject ' ' channel ' ' condition ' ' num2str(min(frequencies)) '-' num2str(max(frequencies)) 'x' num2str(length(times)) '.mat']; %#ok<NOPRT>
                save(filename, 'power', 'channel', 'channelType', 'frequencies', 'times',  'channel', 'channelType', 'subject', 'condition', 'nrOfEpochs', '-v7.3');
                UpdateOrAddTimeFrequencyFileInDatabase(filename, subject, channel, channelType, condition, frequencies, times, nrOfEpochs)
                
            else % zero rows returned..
                %warning('No files for this region/subject. (Skipping..)');
                disp('No electrodes available.');
            end
        end;
    end;
end;
end

function tf = NumbersUnequal(n1, n2)
tf = any(any(n1 ~= n2));
end